<template>
  <div v-if="isMobile">
    <!-- 移动端布局 -->
    <div class="app-container">
      <!-- 左上角图标和文字 -->
      <div class="top-left-logo">
        <div class="logo-icon">
          <span class="lightning">⚡</span>
          <span class="speed-text">速</span>
        </div>
        <p class="logo-text">速图生 - 方便视频工作者</p>
      </div>
      <!-- 内容区域 -->
      <div class="content-wrapper">
        <!-- 左侧内容 -->
        <div class="left-content">
          <HelloWorld 
            :avatarUrl="avatarUrl" 
            :username="username" 
            :title="title" 
            :mainImageUrl="mainImageUrl" 
            :description="description"
            :avatarWidth="avatarWidth"
            :avatarHeight="avatarHeight"
            :mainImageWidth="mainImageWidth"
            :mainImageHeight="mainImageHeight"
            :usernameSize="usernameSize"
            :titleSize="titleSize"
            :descriptionSize="descriptionSize"
            :usernameColor="usernameColor"
            :titleColor="titleColor"
            :descriptionColor="descriptionColor"
          />
        </div>
        <!-- 右侧输入框区域 -->
        <div class="right-content">
          <!-- 名字 -->
          <div class="input-group">
            <label for="username-input">名字：</label>
            <input type="text" id="username-input" v-model="username" />
            <label for="username-size">文字大小：</label>
            <input type="number" id="username-size" v-model="usernameSize" />
            <button @click="decreaseSize('username')">-</button>
            <button @click="increaseSize('username')">+</button>
            <label for="username-color">文字颜色：</label>
            <input type="color" id="username-color" v-model="usernameColor" />
          </div>
          <!-- 上传头像 -->
          <div class="input-group">
            <label for="avatar-input">上传头像：</label>
            <input type="file" id="avatar-input" @change="handleAvatarUpload" />
            <label for="avatar-width">宽度：</label>
            <input type="number" id="avatar-width" v-model="avatarWidth" />
            <label for="avatar-height">高度：</label>
            <input type="number" id="avatar-height" v-model="avatarHeight" />
          </div>
          <!-- 输入主题 -->
          <div class="input-group">
            <label for="theme-input">主题：</label>
            <input type="text" id="theme-input" v-model="theme" />
            <button @click="generateContent" :disabled="isGenerating">
              {{ isGenerating ? '生成中...' : '生成内容和图片' }}
            </button>
          </div>
          <!-- 标题 -->
          <div class="input-group">
            <label for="title-input">标题：</label>
            <input type="text" id="title-input" v-model="title" />
            <label for="title-size">文字大小：</label>
            <input type="number" id="title-size" v-model="titleSize" />
            <button @click="decreaseSize('title')">-</button>
            <button @click="increaseSize('title')">+</button>
            <label for="title-color">文字颜色：</label>
            <input type="color" id="title-color" v-model="titleColor" />
          </div>
          <!-- 正文 -->
          <div class="input-group">
            <label for="description-input">正文：</label>
            <textarea id="description-input" v-model="description"></textarea>
            <label for="description-size">文字大小：</label>
            <input type="number" id="description-size" v-model="descriptionSize" />
            <button @click="decreaseSize('description')">-</button>
            <button @click="increaseSize('description')">+</button>
            <label for="description-color">文字颜色：</label>
            <input type="color" id="description-color" v-model="descriptionColor" />
          </div>
          <!-- 上传作品图 -->
          <div class="input-group">
            <label for="work-image-input">上传作品图：</label>
            <input type="file" id="work-image-input" @change="handleWorkImageUpload" />
            <label for="main-image-width">宽度：</label>
            <input type="number" id="main-image-width" v-model="mainImageWidth" />
            <label for="main-image-height">高度：</label>
            <input type="number" id="main-image-height" v-model="mainImageHeight" />
          </div>
          <!-- 导出格式选择 -->
          <div class="input-group">
            <label for="export-format">导出格式：</label>
            <select id="export-format" v-model="exportFormat">
              <option value="jpg">JPG</option>
              <option value="mp4">MP4</option>
            </select>
          </div>
          <!-- 音乐选择，仅在选择 MP4 时显示 -->
          <div class="input-group" v-if="exportFormat === 'mp4'">
            <label for="music-input">选择音乐：</label>
            <input type="file" id="music-input" @change="handleMusicUpload" accept="audio/*" />
          </div>
          <button @click="exportFile">导出</button>
        </div>
      </div>
      <!-- 底部信息 -->
      <div class="footer">
        <p>凉心开发，1209322734@qq.com</p>
      </div>
    </div>
  </div>
  <div v-else>
    <!-- 网页端布局 -->
    <div class="app-container">
      <!-- 左上角图标和文字 -->
      <!-- <div class="top-left-logo">
        <div class="logo-icon">
          <span class="lightning">⚡</span>
          <span class="speed-text">速</span>
        </div>
        <p class="logo-text">速图生 - 方便视频工作者</p>
      </div> -->
      <!-- 左侧内容 -->
      <div class="left-content fixed-left">
        <HelloWorld 
          :avatarUrl="avatarUrl" 
          :username="username" 
          :title="title" 
          :mainImageUrl="mainImageUrl" 
          :description="description"
          :avatarWidth="avatarWidth"
          :avatarHeight="avatarHeight"
          :mainImageWidth="mainImageWidth"
          :mainImageHeight="mainImageHeight"
          :usernameSize="usernameSize"
          :titleSize="titleSize"
          :descriptionSize="descriptionSize"
          :usernameColor="usernameColor"
          :titleColor="titleColor"
          :descriptionColor="descriptionColor"
        />
      </div>
      <!-- 右侧输入框区域 -->
      <div class="right-content scrollable-right">
        <!-- 名字 -->
        <div class="input-group">
          <label for="username-input">名字：</label>
          <input type="text" id="username-input" v-model="username" />
          <label for="username-size">文字大小：</label>
          <input type="number" id="username-size" v-model="usernameSize" />
          <button @click="decreaseSize('username')">-</button>
          <button @click="increaseSize('username')">+</button>
          <label for="username-color">文字颜色：</label>
          <input type="color" id="username-color" v-model="usernameColor" />
        </div>
        <!-- 上传头像 -->
        <div class="input-group">
          <label for="avatar-input">上传头像：</label>
          <input type="file" id="avatar-input" @change="handleAvatarUpload" />
          <label for="avatar-width">宽度：</label>
          <input type="number" id="avatar-width" v-model="avatarWidth" />
          <label for="avatar-height">高度：</label>
          <input type="number" id="avatar-height" v-model="avatarHeight" />
        </div>
        <div class="input-group">
            <label for="theme-input">主题：</label>
            <input type="text" id="theme-input" v-model="theme" />
            <button @click="generateContent" :disabled="isGenerating">
              {{ isGenerating ? '生成中...' : '生成内容和图片' }}
            </button>
          </div>
        <!-- 上传作品图 -->
        <div class="input-group">
          <label for="work-image-input">上传作品图：</label>
          <input type="file" id="work-image-input" @change="handleWorkImageUpload" />
          <label for="main-image-width">宽度：</label>
          <input type="number" id="main-image-width" v-model="mainImageWidth" />
          <label for="main-image-height">高度：</label>
          <input type="number" id="main-image-height" v-model="mainImageHeight" />
        </div>
        <!-- 标题 -->
        <div class="input-group">
          <label for="title-input">标题：</label>
          <input type="text" id="title-input" v-model="title" />
          <label for="title-size">文字大小：</label>
          <input type="number" id="title-size" v-model="titleSize" />
          <button @click="decreaseSize('title')">-</button>
          <button @click="increaseSize('title')">+</button>
          <label for="title-color">文字颜色：</label>
          <input type="color" id="title-color" v-model="titleColor" />
        </div>
        <!-- 正文 -->
        <div class="input-group">
          <label for="description-input">正文：</label>
          <textarea id="description-input" v-model="description"></textarea>
          <label for="description-size">文字大小：</label>
          <input type="number" id="description-size" v-model="descriptionSize" />
          <button @click="decreaseSize('description')">-</button>
          <button @click="increaseSize('description')">+</button>
          <label for="description-color">文字颜色：</label>
          <input type="color" id="description-color" v-model="descriptionColor" />
        </div>
        <!-- 导出格式选择 -->
        <div class="input-group">
          <label for="export-format">导出格式：</label>
          <select id="export-format" v-model="exportFormat">
            <option value="jpg">JPG</option>
            <option value="mp4">MP4-内测中，目前没兼容</option>
          </select>
        </div>
        <!-- 音乐选择，仅在选择 MP4 时显示 -->
        <div class="input-group" v-if="exportFormat === 'mp4'">
          <label for="music-input">选择音乐：</label>
          <input type="file" id="music-input" @change="handleMusicUpload" accept="audio/*" />
        </div>
        <button @click="exportFile">导出</button>
      </div>
    </div>
    <!-- 底部信息 -->
    <!-- <div class="footer">
      <p>凉心开发，1209322734@qq.com</p>
    </div> -->
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import HelloWorld from './components/HelloWorld.vue';
import html2canvas from 'html2canvas';
// import { createFFmpeg, fetchFile } from '@ffmpeg/ffmpeg';

// 检测是否为移动端
const isMobile = ref(false);
onMounted(() => {
  isMobile.value = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
});

// 定义数据
const username = ref("凉心");
const title = ref("阳光微好，岁月含香");
const description = ref("在忙碌的生活中，我们总是在追寻着什么。而当那一缕缕阳光微好的时刻，时间仿佛都慢了下来。清晨，阳光穿过淡薄的云层，轻柔地洒在窗台的绿植上，叶片上的露珠闪烁着微光，似在诉说着昨夜的美梦。午后，泡一杯清茶，坐在洒满阳光的阳台，翻开一本书，每一页都被阳光染上温暖的色调。黄昏，天边的晚霞被阳光晕染，世界像是被披上了一层薄纱。");
const avatarUrl = ref("");
const mainImageUrl = ref("");
const avatarWidth = ref(50);
const avatarHeight = ref(50);
const mainImageWidth = ref(400);
const mainImageHeight = ref(300);
const usernameSize = ref(16);
const titleSize = ref(24);
const descriptionSize = ref(14);
const usernameColor = ref("#ffffff");
const titleColor = ref("#ffc107");
const descriptionColor = ref("#ffffff");
const theme = ref("");
const KEY = 'sk-ofwgebqoxtutfhoirmiqtwuypqeylxuyqdoppldqixvaufwo';
const isGenerating = ref(false);
const exportFormat = ref('jpg');
const musicFile = ref(null);
const isFFmpegLoading = ref(false);
const isExporting = ref(false);

// 处理头像上传
const handleAvatarUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      avatarUrl.value = e.target.result;
    };
    reader.readAsDataURL(file); 
  }
};

// 处理作品图上传
const handleWorkImageUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      mainImageUrl.value = e.target.result;
    };
    reader.readAsDataURL(file);
  }
};

// 处理音乐上传
const handleMusicUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    musicFile.value = file;
  }
};

// 导出文件
const exportFile = async () => {
  if (isExporting.value) return;
  isExporting.value = true;
  try {
    if (exportFormat.value === 'jpg') {
      const element = document.querySelector('.hello');
      const canvas = await html2canvas(element);
      const dataURL = canvas.toDataURL('image/jpeg');
      const link = document.createElement('a');
      link.href = dataURL;
      link.download = 'exported_image.jpg';
      link.click();
    } else if (exportFormat.value === 'mp4') {
      if (!musicFile.value) {
        alert('请选择音乐文件');
        return;
      }
      // const ffmpeg = createFFmpeg({ log: true });
      // isFFmpegLoading.value = true;
      // await ffmpeg.load();
      // isFFmpegLoading.value = false;

      // 将 HTML 内容转换为图片
      const element = document.querySelector('.hello');
      const canvas = await html2canvas(element);
      const dataURL = canvas.toDataURL('image/jpeg');
      const imgBlob = await (await fetch(dataURL)).blob();

      // 写入图片和音乐文件到 FFmpeg 内存
      // ffmpeg.FS('writeFile', 'image.jpg', await fetchFile(imgBlob));
      // ffmpeg.FS('writeFile', 'music.mp3', await fetchFile(musicFile.value));

      // 执行 FFmpeg 命令，将图片和音乐合并为视频
      // await ffmpeg.run('-loop', '1', '-i', 'image.jpg', '-i', 'music.mp3', '-c:v', 'libx264', '-tune', 'stillimage', '-c:a', 'aac', '-b:a', '192k', '-pix_fmt', 'yuv420p', '-shortest', 'output.mp4');

      // 读取生成的视频文件
      // const videoData = ffmpeg.FS('readFile', 'output.mp4');

      // 创建下载链接
      const videoBlob = new Blob([videoData.buffer], { type: 'video/mp4' });
      const videoUrl = URL.createObjectURL(videoBlob);
      const link = document.createElement('a');
      link.href = videoUrl;
      link.download = 'exported_video.mp4';
      link.click();

      // 释放资源
      URL.revokeObjectURL(videoUrl);
    }
  } catch (error) {
    console.error('导出过程中出现错误:', error);
    alert('导出失败，请稍后重试');
  } finally {
    isExporting.value = false;
  }
};

// 减小文字大小
const decreaseSize = (type) => {
  if (type === 'username') {
    usernameSize.value = Math.max(usernameSize.value - 1, 1);
  } else if (type === 'title') {
    titleSize.value = Math.max(titleSize.value - 1, 1);
  } else if (type === 'description') {
    descriptionSize.value = Math.max(descriptionSize.value - 1, 1);
  }
};

// 增大文字大小
const increaseSize = (type) => {
  if (type === 'username') {
    usernameSize.value++;
  } else if (type === 'title') {
    titleSize.value++;
  } else if (type === 'description') {
    descriptionSize.value++;
  }
};

// 生成内容和图片
const generateContent = async () => {
  if (isGenerating.value) return;
  isGenerating.value = true;
  const inputText = `围绕主题 "${theme.value}" 生成一个吸引人的标题和一段详细的正文内容，标题和正文用换行分隔`;
  // 生成文字内容
  const optionsText = {
    method: 'POST',
    headers: { Authorization: 'Bearer ' + KEY, 'Content-Type': 'application/json' },
    body: JSON.stringify({
      model: "deepseek-ai/DeepSeek-V3",
      messages: [{ role: "user", content: inputText }],
      stream: false,
      max_tokens: 200,
      stop: ["null"],
      temperature: 0.7,
      top_p: 0.7,
      top_k: 50,
      frequency_penalty: 0.5,
      n: 1,
      response_format: { type: "text" },
      tools: [{ type: "function", function: { description: "<string>", name: "<string>", parameters: {}, strict: false } }]
    })
  };
  try {
    const responseText = await fetch('https://api.siliconflow.cn/v1/chat/completions', optionsText);
    const dataText = await responseText.json();
    const result = dataText.choices[0].message.content.split('\n');
    title.value = result[0];
    description.value = result.slice(1).join('\n');
  } catch (err) {
    console.error(err);
  }

  // 生成图片
  const optionsImage = {
    method: 'POST',
    headers: { Authorization: 'Bearer ' + KEY, 'Content-Type': 'application/json' },
    body: JSON.stringify({
      model: "deepseek-ai/Janus-Pro-7B",
      prompt: theme.value,
      seed: 4999999999
    })
  };
  try {
    const responseImage = await fetch('https://api.siliconflow.cn/v1/images/generations', optionsImage);
    const dataImage = await responseImage.json();
    if (dataImage.images && dataImage.images.length > 0) {
      mainImageUrl.value = dataImage.images[0].url;
    } else {
      console.log('未获取到有效的图片 URL');
    }
  } catch (err) {
    console.error(err);
  } finally {
    isGenerating.value = false;
  }
};
</script>

<style scoped>
  /* 移动端样式 */
  @media (max-width: 767px) {
    /* 移动端布局样式 */
    .app-container {
      display: flex;
      flex-direction: column;
      min-height: 100vh;
      background-color: #f4f4f4;
      padding: 10px;
      box-sizing: border-box;
      position: relative;
      padding-bottom: 85px;
    }

    .top-left-logo {
      position: absolute;
      top: 10px;
      left: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding-bottom: 20px;
    }

    .logo-icon {
      display: flex;
      align-items: center;
      font-size: 24px;
      background: linear-gradient(to right, #ff6600, #ffcc00);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }

    .lightning {
      margin-right: -6px;
    }

    .speed-text {
      font-weight: bold;
    }

    .logo-text {
      font-size: 10px;
      color: #333;
      margin-top: 3px;
    }

    .content-wrapper {
      display: flex;
      flex-direction: column;
      flex: 1;
      margin-top: 40px;
    }

    .left-content {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 10px;
    }

    .right-content {
      flex: 1;
      padding: 10px;
      display: flex;
      flex-direction: column;
      gap: 10px;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      overflow-y: auto;
    }

    .input-group {
      display: flex;
      flex-direction: column;
      gap: 5px;
    }

    .input-group label {
      font-weight: bold;
    }

    .input-group input,
    .input-group textarea {
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 4px;
    }

    .input-group button {
      padding: 8px 12px;
      background-color: #007BFF;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      margin-top: 5px;
    }

    .input-group button:hover {
      background-color: #0056b3;
    }

    .footer {
      background-color: #333;
      color: #fff;
      text-align: center;
      padding: 10px 0;
    }
  }

  /* 网页端样式 */
  @media (min-width: 768px) {
    html,
    body {
      height: 100%;
      margin: 0;
      overflow: hidden; /* 禁止整体页面滚动 */
    }

    .app-container {
      display: flex;
      height: 100vh; /* 占据整个视口高度 */
      background-color: #f4f4f4;
      box-sizing: border-box;
      position: relative;
    }

    .top-left-logo {
      position: absolute;
      top: 20px;
      left: 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .logo-icon {
      display: flex;
      align-items: center;
      font-size: 36px;
      background: linear-gradient(to right, #ff6600, #ffcc00);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }

    .lightning {
      margin-right: -8px;
    }

    .speed-text {
      font-weight: bold;
    }

    .logo-text {
      font-size: 12px;
      color: #333;
      margin-top: 5px;
    }

    /* 左侧固定部分 */
    .fixed-left {
      flex: 0 0 30%; /* 左侧固定宽度为 30%，可按需调整 */
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20px;
      overflow: hidden; /* 防止内容溢出 */
    }

    /* 右侧滚动部分 */
    .scrollable-right {
      flex: 1; /* 右侧占据剩余宽度 */
      padding: 20px;
      display: flex;
      flex-direction: column;
      gap: 20px;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      overflow-y: auto; /* 右侧区域可滚动 */
      max-height: 100vh; /* 最大高度为视口高度 */
      padding-bottom: 50px; /* 预留底部信息空间 */
    }

    .input-group {
      display: flex;
      flex-direction: column;
      gap: 5px;
    }

    .input-group label {
      font-weight: bold;
    }

    .input-group input,
    .input-group textarea {
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 4px;
    }

    .input-group button {
      padding: 8px 12px;
      background-color: #007BFF;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      margin-top: 5px;
    }

    .input-group button:hover {
      background-color: #0056b3;
    }

    .footer {
      background-color: #333;
      color: #fff;
      text-align: center;
      padding: 15px 0;
      position: fixed;
      bottom: 0;
      width: 100%;
    }
  }
</style>